import { createStore,combineReducers,applyMiddleware} from "redux";
import thunk from "redux-thunk";
import logger from "redux-logger";
import { useNavigate } from "react-router-dom";
import { LoginApi,Iuser} from "../api";
const initialState = {num:1,user:{}}
interface Iaction {
  type:string
  payload?:any
}
type Inaviage = ReturnType <typeof useNavigate>
function reducer(state=initialState,action:Iaction){
  switch(action.type){
    case "counter/increment":
      return {...state,num:state.num+action.payload}
    case "counter/decrement":
     return {...state,num:state.num-1}
    case "SET_USER":
      return {...state,user:action.payload}
    default:
      return state
  }
 
}
const store = createStore(combineReducers({counter:reducer}),applyMiddleware(thunk,logger))

export default store
export  function increment(v:number):Iaction{
  return {type:"counter/increment",payload:v}
}
export function decrement():Iaction{
  return {type:"counter/decrement"}
}
type Idis = typeof store.dispatch
export type RootState = ReturnType<typeof store.getState>
export function login(data:Iuser,navigate:Inaviage ){
  return (dispatch:Idis)=>{
    LoginApi(data)
    .then(res=>{
      if(res.code===200){        
        dispatch({type:"SET_USER",payload:res.user})
        navigate("/admin")
      }
    })
  }
 
}